/*
 * Copyright 2000-2006 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.intellij.gwt.inspections;

import com.intellij.codeInspection.*;
import com.intellij.gwt.GwtBundle;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.ReadonlyStatusHandler;
import com.intellij.psi.*;
import com.intellij.psi.codeStyle.CodeStyleManager;
import com.intellij.psi.search.GlobalSearchScope;
import com.intellij.psi.util.PsiUtil;
import com.intellij.util.IncorrectOperationException;
import com.intellij.codeHighlighting.HighlightDisplayLevel;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;

public class GwtInconsistentAsyncInterfaceInspection extends LocalInspectionTool {
  @Nullable
  public ProblemDescriptor[] checkClass(final PsiClass aClass, InspectionManager manager, boolean isOnTheFly) {
    if (RemoteServiceUtil.isRemoteServiceInterface(aClass)) {
      return checkRemoteServiceForAsync(aClass, manager);
    }

    final PsiClass synch = RemoteServiceUtil.findSynchronousService(aClass);
    if (synch != null) {
      return checkAsyncServiceForRemote(synch, aClass, manager);
    }

    return null;
  }

  private static ProblemDescriptor[] checkAsyncServiceForRemote(PsiClass sync, PsiClass async, InspectionManager manager) {
    for (PsiMethod method : sync.getMethods()) {
      if (!RemoteServiceUtil.isMethodPresentedInAsync(method, async)) {
        return new ProblemDescriptor[]{
          manager.createProblemDescriptor(async.getNameIdentifier(), GwtBundle.message("problem.description.methods.of.async.remote.service.0.isn.t.synchronized.with.1", async.getName(), sync.getName()),
                                          new QuickFixCopyAllMethods(async, sync), ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
        };
      }
    }

    return null;
  }

  private static ProblemDescriptor[] checkRemoteServiceForAsync(PsiClass aClass, InspectionManager manager) {
    final PsiManager psiManager = PsiManager.getInstance(manager.getProject());
    GlobalSearchScope scope = aClass.getResolveScope();


    final PsiClass async = psiManager.findClass(aClass.getQualifiedName() + RemoteServiceUtil.ASYNC_SUFFIX, scope);
    if (async == null) {
      final String description = GwtBundle.message("problem.description.remote.service.0.doesn.t.have.corresponding.async.variant", aClass.getName());
      return new ProblemDescriptor[] {
        manager.createProblemDescriptor(aClass.getNameIdentifier(), description, new QuickFixNoAsync(aClass), ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
      };
    }

    ArrayList<ProblemDescriptor> result = new ArrayList<ProblemDescriptor>(0);

    for (final PsiMethod method : aClass.getMethods()) {
      if (!RemoteServiceUtil.isMethodPresentedInAsync(method, async)) {
        LocalQuickFix fix = new QuickFixCopyAllMethods(async, aClass);
        String descr = GwtBundle.message("problem.description.async.remote.service.0.doesn.t.define.corresponding.method", async.getName());
        result.add(manager.createProblemDescriptor(method, descr, fix, ProblemHighlightType.GENERIC_ERROR_OR_WARNING));
      }
    }

    return result.toArray(new ProblemDescriptor[result.size()]);
  }

  public String getGroupDisplayName() {
    return GwtInspectionsProvider.GWT_INSPECTIONS_GROUP;
  }

  public String getDisplayName() {
    return GwtBundle.message("inspection.name.inconsistent.gwt.remoteservice");
  }

  public HighlightDisplayLevel getDefaultLevel() {
    return HighlightDisplayLevel.ERROR;
  }

  @NonNls
  public String getShortName() {
    return "GWTRemoteServiceAsyncCheck";
  }

  public boolean isEnabledByDefault() {
    return true;
  }

  private abstract static class MyQuickFix {


  }

  private static class QuickFixCopyAllMethods extends MyQuickFix implements LocalQuickFix {
    private final PsiClass myAsync;
    private final PsiClass myRemoteServiceInterface;


    public QuickFixCopyAllMethods(final PsiClass async, final PsiClass remoteServiceInterface) {
      myAsync = async;
      myRemoteServiceInterface = remoteServiceInterface;
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quick.fix.name.synchronize.all.methods.of.0.with.1", myAsync.getName(), myRemoteServiceInterface.getName());
    }

    @NotNull
    public String getFamilyName() {
      return GwtInspectionsProvider.GWT_QUICKFIXES_FAMILY;
    }

    public void applyFix(@NotNull Project project, ProblemDescriptor descriptor) {
      if (ReadonlyStatusHandler.getInstance(project).ensureFilesWritable(myAsync.getContainingFile().getVirtualFile()).hasReadonlyFiles()) {
        return;
      }

      try {
        RemoteServiceUtil.copyMethodsToAsync(myRemoteServiceInterface, myAsync);
        CodeStyleManager.getInstance(project).reformat(myAsync);
      }
      catch (IncorrectOperationException e) {
      }
    }
  }

  private static class QuickFixNoAsync extends MyQuickFix implements LocalQuickFix {
    private final PsiClass myRemoteServiceInterface;
    private final PsiManager myPsiManager;

    public QuickFixNoAsync(final PsiClass remoteServiceInterface) {
      myRemoteServiceInterface = remoteServiceInterface;
      myPsiManager = remoteServiceInterface.getManager();
    }

    @NotNull
    public String getName() {
      return GwtBundle.message("quick.fix.name.create.interface.0", myRemoteServiceInterface.getName()) + RemoteServiceUtil.ASYNC_SUFFIX;
    }

    @NotNull
    public String getFamilyName() {
      return GwtInspectionsProvider.GWT_QUICKFIXES_FAMILY;
    }

    public void applyFix(@NotNull Project project, ProblemDescriptor descriptor) {
      try {
        final VirtualFile virtualFile = PsiUtil.getVirtualFile(myRemoteServiceInterface);

        PsiJavaFile classFile = (PsiJavaFile)myPsiManager.findFile(virtualFile);
        assert classFile != null;

        final PsiElementFactory psiElementFactory = myPsiManager.getElementFactory();

        final String name = myRemoteServiceInterface.getName() + RemoteServiceUtil.ASYNC_SUFFIX;
        final PsiPackageStatement packageStatement = classFile.getPackageStatement();
        StringBuilder source = new StringBuilder();
        source.append(packageStatement != null ? packageStatement.getText() : "").append("\n\n");
        final PsiImportList psiImportList = classFile.getImportList();
        source.append(psiImportList != null ? psiImportList.getText() : "");
        source.append("public interface ").append(name).append("\n{\n}\n");
        PsiJavaFile asyncFile = (PsiJavaFile)psiElementFactory.createFileFromText(name + ".java", source.toString());

        PsiClass async = asyncFile.getClasses()[0];
        RemoteServiceUtil.copyMethodsToAsync(myRemoteServiceInterface, async);

        CodeStyleManager.getInstance(project).reformat(asyncFile);

        final VirtualFile vfParent = virtualFile.getParent();
        if (vfParent != null) {
          final PsiDirectory directory = myPsiManager.findDirectory(vfParent);
          if (directory != null) directory.add(asyncFile);
        }
      }
      catch (IncorrectOperationException e) {
      }
    }
  }

}
